<template>
  <div style="padding:10px;height:100%; ">
    <el-form :inline="true">

      <el-form-item>
        <el-button
          type="primary"
          @click="add"
          icon="delete"
        >增加</el-button>

      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="remove"
          icon="delete"
        >删除</el-button>
      </el-form-item>
    <slot name="search" />
    </el-form>
    
    <el-table
      style="width:100%"
      :data="list.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      height="500px"
      v-loading="listLoading"
      element-loading-text="Loading"
      ref="table"
      @selection-change="changeFun"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        class="selection"
        prop='uuid'
      ></el-table-column>
      <el-table-column
        align="center"
        type="index"
        width="50"
        label="序号"
        fixed="left"
      >
        <template slot-scope="scope">
          <span>{{(currentPage- 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <DataListItem
        v-bind:key="$index"
        v-for="(item,$index) in cols"
        :column="item"
      />

      <el-table-column
        align="center"
        label="操作"
        width="230"
      >
        <template slot-scope="scope">
          <el-button
            size="small"
            @click="edit(scope.$index, scope.row)"
          >编辑
          </el-button>

        </template>
      </el-table-column>

    </el-table>
    <el-pagination
      align="right"
      style="margin-top:20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[20, 50, 100, 150, 200]"
      :page-size="pageSize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="list.length"
    >
    </el-pagination>
    <EditDlg
      :cancel.sync="showEditDlg"
      :ok.sync="showEditDlg"
      :data="this.model"
      v-if="showEditDlg"
      :cate="cate"
  
      v-on:add="onadd"
      
      v-on:update="onupdate"
      :mode="editMode"
    />
  </div>
</template>
<script>
import Vue from "vue";
import request from "@/utils/request";
import { getUser } from "@/utils/auth";
import EditDlg from "@/components/EditDlg";
import linq from "linq";
import axios from "axios";
import { uuid } from "vue-uuid";
export default {
  props: ["cols", "cate"],
  components: {
    EditDlg,

    DataListItem: {
      name: "DataListItem",
      template: `<el-table-column   :formatter="column.type=='date' && formatDate" :label='column.label' :prop='column.prop' align="center">
          
          <DataListItem :key="$index" v-for="(item,$index) in column.data?column.data:[]" :column="item" />
          </el-table-column>
          `,
          methods:{
             formatDate(row, column, cellValue){
          //return row.date == "2016-05-04" ? '男' : row.sex == 0 ? '女' : '未知';
          //格式化是针对表格内容即使data数据
          var date = row[column.property];
          return new Date(date).toLocaleDateString();
       },
          },
      props: ["column"]
    }
  },
  data: function() {
    return {
      model: {},
      showEditDlg:false,
      listLoading: true,
      list: [],
      raw: [],
      multipleSelectionDelete: [],
      multipleSelection: [],
      currentPage: 1,
      editMode: "add",
      pageSize: 20,
      user: null
    };
  },

  async created() {
    //

    this.listLoading = true;
    let datas = await this.$parent.fetchData();
    this.list = datas;
    this.listLoading = false;

    //
  },

  methods: {
    changeFun(val) {
      this.multipleSelection = val;
    },

    handleSizeChange: function(size) {
      this.pageSize = size;
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },
    add() {
      this.editMode = "add";
      this.model = {};
      this.showEditDlg = true;
      this.$nextTick(_=>{
           this.$parent.onDlgCreated(this.model);
      })
    },
    async onchange(model, field, e) {
      this.$parent.onChange ? this.$parent.onChange(model, field, e) : "";
    },
    // onDlgCreated() {
    //   this.$parent.onDlgCreated ? this.$parent.onDlgCreated(this.model) : "";
    // },
    async onadd(model) {
        try {
      Object.keys(model).forEach(k => {
        if (model[k] == null) {
          delete model[k];
        }
        if (model[k] && model[k] === "") {
          delete model[k];
        }
      });
      if(this.$parent.add_check){
        var ss = this.$parent.add_check(model,this.list);
        
        if(ss)
        throw ss;
      }
      var result = await this.$parent.onadd(model);
      this.list.push(result);
      this.showEditDlg = false;
       }catch(e){
         console.log("catch e");
         this.$alert(e);
       }
    },
    
    async onupdate(model) {
      try {
        console.log("before update11  "+JSON.stringify(model))
        await this.$parent.onupdate(model);
       
        Vue.set(this.list, this.editIndex, model)
        console.log("after update "+JSON.stringify(model))
        this.showEditDlg = false;
      } catch (e) {
        this.$alert(e);
      }
    },
    edit(index, row) {
      //
      
      this.editIndex = index;
      this.selectRow = row;
      this.editMode = "update";
     
      this.model = JSON.parse(JSON.stringify(row));
      
      this.showEditDlg = true;
      this.$nextTick(_=>{
           this.$parent.onDlgCreated(this.model);
      })
     
     
    },

    remove() {
      this.$confirm("你确定是否删除").then(async e => {
         try {
          await Promise.all(
            this.multipleSelection.map(async (item, index) => {
              await this.$parent.ondelete(item);
            })
          );
          this.listLoading = true;
          let datas = await this.$parent.fetchData();
          this.list = datas;
          this.listLoading = false;
        } catch (e) {
          this.$alert(e);
        }
      });
    }
  }
};
</script>